package cn.usian.controller;

import cn.usian.common.R;
import cn.usian.entity.Employee;
import cn.usian.service.EmployeeService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /*@RequestMapping("/login")
    public Employee login(@RequestBody Employee loginForm){
        return employeeService.login(loginForm);
    }*/

    //登录功能
    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        R<Employee> r = employeeService.login(employee);
        if (r.getCode()==1){
            session.setAttribute("employee",r.getData().getId());
        }
        return r;
    }

    //退出登录
    @RequestMapping("/logout")
    public R<String> logout(HttpSession request){
        request.removeAttribute("employee");
        return R.success("退出成功");
    }

    //员工信息展示
    @RequestMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        return employeeService.page(page,pageSize,name);
    }

    //添加功能
    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){
       long id =(long) session.getAttribute("employee");
       //将创建者的id保存在employee对象中
       employee.setCreateUser(id);
       employee.setUpdateUser(id);
       employeeService.save(employee);
       return R.success("添加成功");
    }

    //修改功能
    @PutMapping
    public R updateEmp(@RequestBody Employee employee,HttpSession session){
        long id = (long) session.getAttribute("employee");
        employee.setUpdateUser(id);
        employeeService.updateEmp(employee);
        return R.success("修改成功");
    }

    //回显功能
    @GetMapping("{id}")
    public R findById(@PathVariable long id){
        return employeeService.findById(id);
    }
}
